package com.ytjj.qmyx.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.constants.CopyWriterConstant;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.utils.CopyWriterConfigUtil;
import com.ytjj.qmyx.admin.dao.ImgTaskDao;
import com.ytjj.qmyx.admin.model.*;
import com.ytjj.qmyx.admin.model.request.ImgRecordRequest;
import com.ytjj.qmyx.admin.model.request.ImgTaskUploadRequest;
import com.ytjj.qmyx.admin.model.response.ImgLibraryResponse;
import com.ytjj.qmyx.admin.model.response.SelectProductSkuInfoResponse;
import com.ytjj.qmyx.admin.service.ImgTaskService;
import com.ytjj.qmyx.admin.service.MemberService;
import com.ytjj.qmyx.mall.mapper.*;
import com.ytjj.qmyx.mall.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @ClassName ImgTaksServiceImpl
 *
 *
 * @Version 1.0
 **/
@Service
@Slf4j
public class ImgTaskServiceImpl implements ImgTaskService {
    @Resource
    private ImgLibraryMapper imgLibraryMapper;
    @Resource
    private ImgTaskDao imgTaskDao;
    @Resource
    private MemberService memberService;
    @Resource
    private CopyWriterConfigUtil copyWriterConfigUtil;
    @Resource
    private ProductSelectImgMapper productSelectImgMapper;
    @Resource
    private ProductSelectSkuKeyMapper productSelectSkuKeyMapper;
    @Resource
    private ProductSelectSkuValueMapper productSelectSkuValueMapper;
    @Resource
    private ProductAttributeKeyMapper productAttributeKeyMapper;
    @Resource
    private ProductAttributeValueMapper productAttributeValueMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addImg(ImgTaskUploadRequest imgTaskUploadRequest) {
        int count = 0;
        if (!CollectionUtils.isEmpty(imgTaskUploadRequest.getImgUrls())) {
            for (Map<String, String> param : imgTaskUploadRequest.getImgUrls()) {
                String name = param.get("name").substring(0, param.get("name").indexOf("."));
                Integer num = 0;
                if (imgTaskUploadRequest.getFileType().equals("img") && !name.equals("0")) {
                    try {
                        num = Integer.parseInt(name);
                    } catch (RuntimeException e) {
                        throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.FILE_NAME_MUST_NUMBER));
                    }
                } else {
                    num = 1;
                }

                Admin admin = memberService.getAdmin();
                // img_library库
                ImgLibrary imgLibrary = new ImgLibrary();
                imgLibrary.setImg(param.get("url"));
                imgLibrary.setProductId(imgTaskUploadRequest.getProductId());
                imgLibrary.setType(imgTaskUploadRequest.getType());
                imgLibrary.setFileType(imgTaskUploadRequest.getFileType());
                imgLibrary.setCreateTime(new Date());
                imgLibrary.setSort(num);
                imgLibrary.setVideo(imgTaskUploadRequest.getVideo());
                imgLibrary.setDynamicId(imgTaskUploadRequest.getDynamicId());
                imgLibrary.setUserId(admin.getId());
                imgLibrary.setUserName(admin.getName());
                imgLibrary.setOperateType("ADD");
                count = imgLibraryMapper.insertSelective(imgLibrary);
                // product_select_img库
                ProductSelectImg productSelectImg = new ProductSelectImg();
                productSelectImg.setUserId(admin.getId());
                productSelectImg.setUserName(admin.getName());
                productSelectImg.setImg(param.get("url"));
                productSelectImg.setProductLibraryId(imgTaskUploadRequest.getProductId());
                productSelectImg.setType(imgTaskUploadRequest.getType());
                productSelectImg.setFileType(imgTaskUploadRequest.getFileType());
                productSelectImg.setCreateTime(new Date());
                productSelectImg.setSort(num);
                productSelectImgMapper.insertSelective(productSelectImg);
            }
        } else {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.FILE_NOT_NULL));
        }
        return count;
    }

    @Override
    public CommonPage<ProductSelectImg> getImgList(ImgTaskUploadRequest imgTaskUploadRequest) {
        PageHelper.startPage(imgTaskUploadRequest.getPageNum(), imgTaskUploadRequest.getPageSize());
        List<ProductSelectImg> productSelectImgList = Optional.ofNullable(imgTaskDao.getSelectImgLisgt(imgTaskUploadRequest))
                .orElseGet(() -> Collections.emptyList());
        return CommonPage.restPage(productSelectImgList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteImg(Integer id) {
        Admin admin = memberService.getAdmin();
        return imgTaskDao.updateImgStatus(id, admin.getId(), admin.getName());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int modifiedImgInfo(ImgTaskUploadRequest imgTaskUploadRequest) {
        Admin admin = memberService.getAdmin();
        // 新增新的商品记录
        ImgLibrary imgLibrary = new ImgLibrary();
        imgLibrary.setUserId(admin.getId());
        imgLibrary.setProductId(imgTaskUploadRequest.getProductId());
        imgLibrary.setUserName(admin.getName());
        imgLibrary.setType(imgTaskUploadRequest.getType());
        imgLibrary.setImg(imgTaskUploadRequest.getImg());
        imgLibrary.setFileType(imgTaskUploadRequest.getFileType());
        imgLibrary.setSort(imgTaskUploadRequest.getSort());
        imgLibrary.setCreateTime(imgTaskUploadRequest.getCreateTime());
        imgLibrary.setOperateType("MODIFIED");
        imgLibraryMapper.insertSelective(imgLibrary);
        // 修改图片
        imgTaskUploadRequest.setUpdateTime(new Date());
        return imgTaskDao.modifiedImgInfo(imgTaskUploadRequest);
    }


    @Override
    public List<SelectProductSkuInfoResponse> getSelectProductSkuInfo(Integer id) {
        ProductSelectSkuKeyExample productSelectSkuKeyExample = new ProductSelectSkuKeyExample();
        productSelectSkuKeyExample.createCriteria()
                .andPidEqualTo(id);
        List<ProductSelectSkuKey> productSelectSkuKeyList = productSelectSkuKeyMapper.selectByExample(productSelectSkuKeyExample);
        if(productSelectSkuKeyList != null && productSelectSkuKeyList.size() > 0) {
            return productSelectSkuKeyList.stream()
                    .map(item -> {
                        SelectProductSkuInfoResponse selectProductSkuInfoResponse = new SelectProductSkuInfoResponse(item);
                        ProductSelectSkuValueExample productSelectSkuValueExample = new ProductSelectSkuValueExample();
                        productSelectSkuValueExample.createCriteria()
                                .andKidEqualTo(item.getId())
                                .andPidEqualTo(item.getPid())
                                .andStatusEqualTo((byte) 1);
                        List<ProductSelectSkuValue> productSelectSkuValues = Optional.ofNullable(productSelectSkuValueMapper.selectByExample(productSelectSkuValueExample))
                                .orElse(new ArrayList<>());
                        selectProductSkuInfoResponse.setSkuValue(productSelectSkuValues);
                        return selectProductSkuInfoResponse;
                    }).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public Map<String, Object> selectSkuKeysbypid(Integer id) {

        Map<String, Object> map = new HashMap<>();

        // 查询商品选择的属性 key 集合
        ProductSelectSkuKeyExample productSelectSkuKeyExample = new ProductSelectSkuKeyExample();
        productSelectSkuKeyExample.createCriteria().andPidEqualTo(id);
        List<ProductSelectSkuKey> productSelectSkuKeyList = productSelectSkuKeyMapper.selectByExample(productSelectSkuKeyExample);

        // 查询商品选择的属性 value 集合
        ProductSelectSkuValueExample productSelectSkuValueExample = new ProductSelectSkuValueExample();
        productSelectSkuValueExample.createCriteria().andPidEqualTo(id);
        List<ProductSelectSkuValue> productSelectSkuValues = productSelectSkuValueMapper.selectByExample(productSelectSkuValueExample);
        List<Integer> checkedIds = productSelectSkuValues.stream().map(ProductSelectSkuValue::getAttributeValueId).collect(Collectors.toList());

        // 查询选择的属性key的所有value集合
        List<Map<String, Object>> spec_array = new ArrayList<>();
        if (!CollectionUtils.isEmpty(productSelectSkuKeyList)) {
            List<Integer> attributeKeyIds = productSelectSkuKeyList.stream().map(ProductSelectSkuKey::getAttributeKeyId).collect(Collectors.toList());
            for (Integer attributeKeyId : attributeKeyIds) {
                Map<String, Object> spec_map = new LinkedHashMap<>();
                Map<String, Object> spanKeys_map = new LinkedHashMap<>();
                ProductAttributeKey productAttributeKey = productAttributeKeyMapper.selectByPrimaryKey(attributeKeyId);
                ProductAttributeValueExample productAttributeValueExample = new ProductAttributeValueExample();
                productAttributeValueExample.createCriteria().andAttributeIdEqualTo(productAttributeKey.getId());
                List<ProductAttributeValue> productAttributeValues = productAttributeValueMapper.selectByExample(productAttributeValueExample);
                spanKeys_map.put("id", "p" + productAttributeKey.getId());
                spanKeys_map.put("name", productAttributeKey.getAttributeName());
                spec_map.put("spanName", spanKeys_map);
                if (!CollectionUtils.isEmpty(productAttributeValues)) {
                    List<Map<String, Object>> spanValues = new ArrayList<>();
                    for (ProductAttributeValue productAttributeValue : productAttributeValues) {
                        Map<String, Object> spanValues_map = new HashMap<>();
                        spanValues_map.put("id", productAttributeValue.getId());
                        spanValues_map.put("name", productAttributeValue.getAttributeValue());
                        spanValues.add(spanValues_map);
                    }
                    spec_map.put("spanValue", spanValues);
                }
                spec_array.add(spec_map);
            }
        }
        map.put("checkeds", checkedIds);
        map.put("keys", spec_array);
        return map;
    }

    @Override
    public CommonPage<ImgLibraryResponse> getImgRecordList(ImgRecordRequest imgRecordRequest) {
        PageHelper.startPage(imgRecordRequest.getPageNum(), imgRecordRequest.getPageSize());
        return CommonPage.restPage(imgTaskDao.selectImgList(imgRecordRequest));
    }


}
